<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>WebSocket</title>
    <script type="text/javascript">

        var ws = null;
        var connect = false;
        var close = false;

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        };

        //将消息显示在网页上
        function print(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML+ '<br/>';
        }

        function clear() {
            document.getElementById('message').innerHTML = '';
        }

        function closeWebSocket() {
            connect = false
            close = true
            ws.close()
        }

        function send() {
            if (connect) {
                var message = document.getElementById('text').value;
                ws.send(message);
                print("[发送] " + message)
            } else {
                print("未连接...")
            }
        }


        function sleep(numberMillis) {
            var now = new Date();
            var exitTime = now.getTime() + numberMillis;
            while (true) {
                now = new Date();
                if (now.getTime() > exitTime) {
                    return;
                }
            }
        }


        function runWebSocket() {

            //获取连接地址
            var url = document.getElementById('url').value;

            if (connect) {
                closeWebSocket();
            }

            ws = new WebSocket(url);

            //连接发生错误的回调方法
            ws.error = function () {
                print("连接错误...");
            };

            ws.onopen = function () {
                connect = true
                print("连接成功...");
            };

            ws.onmessage = function (msg) {
                //document.getElementById('img').src ="data:image/png;base64,"+ msg.data
                print(msg.data);
            };

            ws.onclose = function () {
                print("连接已关闭...");
                if (!close) {
                    sleep(2000);
                    runWebSocket();
                }
            };


        }

    </script>

</head>
<body>

<div id="sse">
    <input id="url" type="text" value="ws://192.168.10.24:10001/api/ai/photo/ws?key=0" style="width:500px"/>
    <button onclick="runWebSocket()">链接</button>
    <button onclick="closeWebSocket()">断开</button>
    <br/>
    <input id="text" type="text" style="width:500px"/>
    <button onclick="send()">发送</button>
    <button onclick="clear()">清理</button>
    <br/>
    <img id="img" src=""/>
    <br/>
    <div id="message"></div>
</div>

</body>
</html>